package handle

import (
	g "blog.wuzhispace.com/internal/global"
	"blog.wuzhispace.com/internal/model"
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/redis/go-redis/v9"
	"golang.org/x/exp/slog"
)

type Page struct {
}

func (p Page) GetList(c *gin.Context) {
	db := GetDB(c)
	rdb := GetRDB(c)
	//	从缓存中取数据
	cache, err := getPageCache(rdb)
	if cache != nil && err == nil {
		slog.Debug("[handle-page-GetList] get page list from cache")
		ReturnSuccess(c, cache)
		return
	}

	switch {
	case errors.Is(err, redis.Nil):
		break
	default:
		ReturnError(c, g.ErrRedisOp, err)
		return
	}

	//	从数据库中取数据
	pages, _, err := model.GetPageList(db)
	if err != nil {
		ReturnError(c, g.ErrDbOp, err)
		return
	}

	//	将数据存入缓存
	if err := AddPageCache(rdb, pages); err != nil {
		ReturnError(c, g.ErrRedisOp, err)
		return
	}
	ReturnSuccess(c, pages)
}

func (p Page) SaveOrUpdate(c *gin.Context) {
	var req model.Page
	if err := c.ShouldBindJSON(&req); err != nil {
		ReturnError(c, g.ErrRequest, err)
		return
	}

	db := GetDB(c)
	rdb := GetRDB(c)

	page, err := model.SaveOrUpdatePage(db, req.ID, req.Name, req.Label, req.Cover)
	if err != nil {
		ReturnError(c, g.ErrDbOp, err)
		return
	}

	//	 删除缓存
	if err := removePageCache(rdb); err != nil {
		ReturnError(c, g.ErrRedisOp, err)
		return
	}
	ReturnSuccess(c, page)
}

func (p Page) Delete(c *gin.Context) {
	var ids []int
	if err := c.ShouldBindJSON(&ids); err != nil {
		ReturnError(c, g.ErrRequest, err)
		return
	}
	result := GetDB(c).Delete(&model.Page{}, "id in ?", ids)
	if result.Error != nil {
		ReturnError(c, g.ErrDbOp, result.Error)
		return
	}
	//	 删除缓存
	rdb := GetRDB(c)
	if err := removePageCache(rdb); err != nil {
		ReturnError(c, g.ErrRedisOp, err)
		return
	}
	ReturnSuccess(c, result.RowsAffected)
}
